package org.begincode.web;

import com.begincode.common.util.ResultUtil;
import org.begincode.core.model.WordChapter;
import org.begincode.course.handler.ChapterHandler;
import org.begincode.course.handler.CourseHandler;
import org.begincode.task.queue.CountOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by yangsj on 2016/5/1.
 * 章节
 */
@Controller
@RequestMapping("chapter")
public class ChapterController {
    @Resource
    private ChapterHandler chapterHandler;
    @Resource
    private CourseHandler courseHandler;
    @Autowired
    CountOperator countOperator;

    @RequestMapping(value="/course/{courseId}/0" , method = RequestMethod.GET)
    public String chapterList(Model model,@PathVariable("courseId") int courseId){
        List<WordChapter> wordChapterList = chapterHandler.getWordChaptersByCourseId(courseId);
        model.addAttribute("course",courseHandler.getCourseById(courseId));
        model.addAttribute("wordChapters",wordChapterList);
        if(!CollectionUtils.isEmpty(wordChapterList)){
            model.addAttribute("chapter",chapterHandler.getWordChapterById(wordChapterList.get(0).getWordChapterId()));
        }
        //新增浏览次数
        countOperator.addCourseViewCount(courseId);
        return "/page/courseWord_view";
    }

    @RequestMapping(value="/course/{courseId}/{chapterId}" , method = RequestMethod.GET)
    public String chapterList(Model model,@PathVariable("courseId") int courseId,@PathVariable("chapterId") int chapterId){
        List<WordChapter> wordChapterList = chapterHandler.getWordChaptersByCourseId(courseId);
        model.addAttribute("course",courseHandler.getCourseById(courseId));
        model.addAttribute("wordChapters",wordChapterList);
        model.addAttribute("chapter",chapterHandler.getWordChapterById(chapterId));
        //新增浏览次数
        countOperator.addCourseViewCount(courseId);
        return "/page/courseWord_view";
    }

    @RequestMapping(value="/{chapterId}" , method = RequestMethod.GET)
    @ResponseBody
    public Object chapter(@PathVariable("chapterId") int chapterId){
        WordChapter wordChapter= chapterHandler.getWordChapterById(chapterId);
        return ResultUtil.buildSuccess(wordChapter);
    }


}
